package org.CGlibProxyEnhancer;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGlib动态代理，可以代理无接口的类
 *
 * Created by chinalin on 2017/3/17.
 */
public class CGLibDynamicProxy implements MethodInterceptor{
    private CGLibDynamicProxy() {
    }

    private static CGLibDynamicProxy instance = new CGLibDynamicProxy() ;

    public static CGLibDynamicProxy getInstance(){
        return instance ;
    }
    public <T> T getProxy(Class<T> cls){
        return (T) Enhancer.create(cls,this) ;
    }

    public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        before();
        Object result = proxy.invokeSuper(target,args) ;
        after();
        return result;
    }
    private void before(){
        System.out.println("before");
    }
    private void after(){
        System.out.println("after");
    }
}
